package com.ming.javaweb.dao.impl;

import com.ming.javaweb.dao.AdminDao;
import com.ming.javaweb.beans.entity.AdminDO;
import com.ming.javaweb.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminDaoImpl implements AdminDao {
    @Override
    public AdminDO validateLogin(String usreName) throws SQLException {
        Connection conn = JDBCUtil.getConn();
        if (conn == null){
            return null;
        }
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select * from admin where user_name = ? ");
        try {
            preparedStatement = conn.prepareStatement(stringBuilder.toString());
            preparedStatement.setObject(1,usreName);
//            打印最终执行的sql语句
            System.out.println("validateLogin执行的sql："+preparedStatement.toString());
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                int id = resultSet.getInt("id");
                String pwd = resultSet.getString("pwd");
                AdminDO adminDO = new AdminDO();
                adminDO.setId(id);
                adminDO.setUserName(usreName);
                adminDO.setPwd(pwd);
                return adminDO;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.closeResultSet(resultSet);
            JDBCUtil.closePs(preparedStatement);
            JDBCUtil.closeConn(conn);
        }
        return null;
    }

    @Override
    public void register(AdminDO adminDO) throws SQLException {
        Connection conn = JDBCUtil.getConn();
        if (conn == null){
            return;
        }
        PreparedStatement ps = null;
        ResultSet ts = null;
        StringBuilder sb = new StringBuilder();
        sb.append("insert into admin(user_name,pwd) ");
        sb.append("values(?,?)");
        try {
            ps = conn.prepareStatement(sb.toString());
            ps.setObject(1,adminDO.getUserName());
            ps.setObject(2,adminDO.getPwd());
            System.out.println("register执行的sql："+ps.toString());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.closePs(ps);
            JDBCUtil.closeConn(conn);
        }
    }
}
